<?php

App::uses('AppController', 'Controller');

class ListsController extends AppController {
	
	public $uses = array('City', 'Category', 'Tag');
	
	private $lists = array(
		'cities' => 'City',
		'categories' => 'Category',
		'tags' => 'Tag'
	);
	
	private $modelTag;
	private $modelName;
	private $Model;
	
	public function beforeFilter() {
		parent::beforeFilter();
		if( isset($this->params['model']) ) {
			$this->modelTag = $this->params['model'];
			$this->modelName = $this->lists[$this->modelTag];
			$this->Model = $this->{$this->modelName};
			$this->set('modelName', $this->modelName);
			$this->set('modelTag', $this->modelTag);
		}
	}
	
	public function index() {
		
		$this->set('list', $this->Model->find('all', array (
			'order' => 'name ASC'
		)));
		
	}
	
	public function add() {
		if ($this->request->is('post')) {
			$this->Model->create();
			if ($this->Model->save($this->request->data)) {
				$this->Session->setFlash( __("List Item saved.") );
				$this->redirect(array('action' => $this->modelTag, 'admin' => true));
			}
			else {
				$this->Session->setFlash( __("Couldn't save the List Item. Please, try again.") );
			}
		}
	}
	
	public function edit($id) {
		$this->Model->id = $id;
		
		if (!$this->Model->exists()) {
			throw new NotFoundException( __("Invalid List Item.") );
		}
		
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Model->save($this->request->data)) {
				$this->Session->setFlash( __("List Item saved.") );
				$this->redirect(array('action' => $this->modelTag, 'admin' => true));
			}
			else {
				$this->Session->setFlash( __("Couldn't save the List Item. Please, try again.") );
			}
		}
		else {
			$this->request->data = $this->Model->read(null, $id);
		}
	}
	
	public function delete($id) {
		$this->Model->id = $id;
		
		if (!$this->Model->exists()) {
			throw new NotFoundException( __("Invalid List Item.") );
		}
		
		if ($this->Model->delete()) {
			$this->Session->setFlash( __("List Item deleted.") );
			$this->redirect(array('action' => $this->modelTag, 'admin' => true));
		}
		
		$this->Session->setFlash( __("Couldn't delete the List Item. Please, try again.") );
		
		$this->redirect(array('action' => $this->modelTag, 'admin' => true));
	}
	
}